/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dafe.springlink;

import java.io.IOException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 *
 * @author dafe
 */
public final class ServiceLocator {

    private final GenericApplicationContext ctx;
    private static final ServiceLocator instance = new ServiceLocator();

    public static ServiceLocator getInstance() {
        return instance;
    }

    public Object getBean(String beanName) {
        return this.ctx.getBean(beanName);
    }

    private ServiceLocator() {
        this.ctx = new GenericApplicationContext() {

            @Override
            protected ResourcePatternResolver getResourcePatternResolver() {
                return new PathMatchingResourcePatternResolverEx(this);
            }
        };

        //set Spring's classloader to context classloader
        this.ctx.setClassLoader(Thread.currentThread().getContextClassLoader());

        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("appConfig.xml", ServiceLocator.class));
//        xmlReader.getBeanFactory().getBeanDefinition(null);
        ctx.refresh();
    }

    private static class PathMatchingResourcePatternResolverEx extends PathMatchingResourcePatternResolver {

        public PathMatchingResourcePatternResolverEx(ResourceLoader resourceLoader) {
            super(resourceLoader);
        }

        public PathMatchingResourcePatternResolverEx(ClassLoader classLoader) {
            super(classLoader);
        }

        public PathMatchingResourcePatternResolverEx() {
            super();
        }

        @Override
        protected boolean isJarResource(Resource resource) throws IOException {
            return super.isJarResource(resource) || "nbjcl".equals(resource.getURL().getProtocol());
        }
    }
}
